package main
import (
	"fmt"
	"gopkg.in/redis.v4"
	"time"
)
//Golang操作Redis的第二种方式：import "gopkg.in/redis.v4"
func main(){
	client := createClient()
	stringOperation(client)
	listOperation(client)
	setOperation(client)
	hashOperation(client)
}

//创建redis客户端
func createClient() *redis.Client{
	client := redis.NewClient(&redis.Options{
		Addr : "localhost:6379",
		Password : "",
		DB : 0,
	})

	//通过client.Ping() 来检查是否连接成功到redis服务
	pong,err := client.Ping().Result()
	fmt.Println(pong,err)
	return client
}

//关于String的操作
func stringOperation(client *redis.Client){
	//第三个参数时过期时间，如果是0，则表示没有过期时间。
	err := client.Set("name","lsx",0).Err()
	if err != nil{
		panic(err)
	}

	val,err := client.Get("name").Result()
	if err != nil{
		panic(err)
	}
	fmt.Println("name:",val)

	err = client.Set("age",20,1*time.Second).Err()
	if err != nil{
		panic(err)
	}

	client.Incr("age")//自增
	client.Incr("age")
	client.Decr("age")//自减

	val,err = client.Get("age").Result()
	if err != nil{
		panic(err)
	}
	fmt.Println("age : ",val)

	//因为上面的age的过期时间时1秒钟，因此当一秒后，该key会被删除
	time.Sleep(1 * time.Second)
	val,err = client.Get("age").Result()
	if err != nil{
		fmt.Println("error :",err)
	}
	fmt.Println("age : ---",val)
}

//链表list的相关操作
func listOperation(client *redis.Client){
	client.RPush("fruit","apple")
	client.LPush("fruit","banana")
	len,err := client.LLen("fruit").Result()
	if err != nil {
		panic(err)
	}
	fmt.Println("length: ",len)
	value,err := client.LPop("fruit").Result();
	if err != nil{
		panic(err)
	}
	fmt.Println("fruit: ",value)
	value,err = client.RPop("fruit").Result();
	if err != nil{
		panic(err)
	}
	fmt.Println("fruit: ",value)
}

//set相关操作
func setOperation(client *redis.Client){
	client.SAdd("blacklist","Obama")
	client.SAdd("blacklist","Hillary")
	client.SAdd("blacklist","the Elder")
	client.SAdd("whitelist","the Elder")
	//判断元素是否在集合中
	isMember,err := client.SIsMember("blacklist","Bush").Result()
	if err != nil{
		panic(err)
	}
	fmt.Println("Is Bush in blacklist: ",isMember)

	names,err := client.SInter("blacklist","whitelist").Result()
	if err != nil{
		panic(err)
	}
	fmt.Println("Inter result: ",names)

	//获取指定集合的所有元素
	all,err := client.SMembers("blacklist").Result()
	if err != nil{
		panic(err)
	}
	fmt.Println("All member: ",all)
}

//hash操作
func hashOperation(client *redis.Client){
	client.HSet("user_xys","name","yxs")
	client.HSet("user_xys","age","18")
	client.HMSet("user_test",map[string]string{
		"name":"test",
		"age":"20",
	})
	//获取多个字段值
	fields,err := client.HMGet("user_test","name","age").Result()
	if err != nil{
		panic(err)
	}
	fmt.Println("fields in user_test: ",fields)

	//获取名为user_xys的hash中的字段个数
	length,err := client.HLen("user_xys").Result()
	if err != nil{
		panic(err)
	}
	fmt.Println("field count in user_xys: ",length) //字段个数

	client.HDel("user_test","age")

	age,err := client.HGet("user_test","age").Result()
	if err != nil{
		fmt.Println("Get user_test are error: ",err)
	}else{
		fmt.Println("user_test age is :",age)
	}
}